package com.yonyougov.devops.cruxcisupport.component;

import com.yonyougov.devops.cruxcisupport.app.AppEntity;
import com.yonyougov.devops.cruxcisupport.app.AppService;
import com.yonyougov.devops.cruxcisupport.appenv.AppEnvEntity;
import com.yonyougov.devops.cruxcisupport.appenv.AppEnvService;
import com.yonyougov.devops.cruxcisupport.env.EnvEntity;
import com.yonyougov.devops.cruxcisupport.env.EnvService;
import com.yonyougov.devops.cruxcisupport.rancher.response.PodsResponse;
import com.yonyougov.devops.cruxcisupport.rancher.response.ProjectsResponse;
import com.yonyougov.devops.cruxcisupport.rancher.vo.RhContainer;
import com.yonyougov.devops.cruxcisupport.rancher.vo.RhLabels;
import com.yonyougov.devops.cruxcisupport.rancher.vo.RhPod;
import com.yonyougov.devops.cruxcisupport.rancher.vo.RhProject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@Component
@Slf4j
public class RhTask {


    @Value("${rh.bear-token}")
    private String bearToken;
    @Value("${rh.api}")
    private String rhApi;
    private EnvService envService;
    private AppService appService;
    private AppEnvService appEnvService;

    public RhTask(EnvService envService, AppService appService, AppEnvService appEnvService) {
        this.envService = envService;
        this.appService = appService;
        this.appEnvService = appEnvService;
    }

    @SneakyThrows
    public void sync(String envName) {
        // 获取当前用户的id
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization", "Bearer " + bearToken);
        httpHeaders.add("Context-Type", "application/json");
        RequestEntity requestEntity = new RequestEntity(httpHeaders, HttpMethod.GET, new URI(rhApi + "/projects"));
        ResponseEntity<ProjectsResponse> projectsResponseEntity = restTemplate.exchange(requestEntity, ProjectsResponse.class);
        if (projectsResponseEntity.getStatusCodeValue() != 200) {
            log.error("1获取projects失败,http status:{},body:{}", projectsResponseEntity.getStatusCodeValue(), projectsResponseEntity.getBody());
            return;
        }
        ProjectsResponse projectsResponse = projectsResponseEntity.getBody();
        if (projectsResponse == null) {
            log.error("2获取projects失败,http status:{},body:{}", projectsResponseEntity.getStatusCodeValue(), projectsResponseEntity.getBody());
            return;
        }
        for (RhProject datum : projectsResponse.getData()) {
            if (!envName.equals(datum.getName())) {
                continue;
            }
            EnvEntity envEntity = new EnvEntity();
            envEntity.setName(datum.getName());
            EnvEntity env = envService.findBy(envEntity);
            if (null != env) {
                log.debug("更新环境:{}容器状态", env.getName());
                RequestEntity podReq = new RequestEntity(httpHeaders, HttpMethod.GET, new URI(rhApi + "/projects/" + datum.getId() + "/pods"));
                ResponseEntity<PodsResponse> podRep = restTemplate.exchange(podReq, PodsResponse.class);
                if (podRep.getStatusCodeValue() != 200) {
                    log.error("1获取pods失败,http status:{},body:{}", podRep.getStatusCodeValue(), podRep.getBody());
                    continue;
                }
                if (podRep.getBody() == null) {
                    log.error("2获取pods失败,http status:{},body:{}", podRep.getStatusCodeValue(), podRep.getBody());
                    continue;
                }
                for (RhPod rhPod : podRep.getBody().getData()) {
                    RhLabels labels = rhPod.getLabels();
                    if (labels == null || labels.getApp() == null) {
                        log.error("pod:{} labels 不存在！", rhPod.getName());
                        continue;
                    }
                    AppEntity appEntity = new AppEntity();
                    appEntity.setApp(labels.getApp());
                    AppEntity app = appService.findBy(appEntity);
                    AppEnvEntity appEnvEntityParam = new AppEnvEntity();
                    appEnvEntityParam.setEnvId(env.getId());
                    appEnvEntityParam.setAppId(app.getId());
                    AppEnvEntity oldAppEnvEntity = appEnvService.findBy(appEnvEntityParam);
                    List<RhContainer> containers = rhPod.getContainers();
                    int total = containers.size();
                    int runNum = 0;
                    int restartNum = 0;
                    for (RhContainer container : containers) {
                        if ("running".equals(container.getState())) {
                            runNum++;
                        }
                        restartNum += container.getRestartCount();
                    }
                    String state = rhPod.getState();
                    AppEnvEntity appEnvEntity = new AppEnvEntity();
                    BeanUtils.copyProperties(oldAppEnvEntity, appEnvEntity);
                    appEnvEntity.setContainerTotal(total);
                    appEnvEntity.setRunContainerNum(runNum);
                    appEnvEntity.setRestartNum(restartNum);
                    appEnvEntity.setState(state);
                    appEnvService.update(appEnvEntity);
                    log.debug("app:{}在环境:{}下更新状态成功", labels.getApp(), env.getName());
                }
            }
        }
    }
}
